package com.is.control;

import java.sql.ResultSet;

import com.is.dbconn.DBConnect;
import com.is.model.DictationTime;
import com.is.util.DateTime;

public class DictationTimeControl {
	//插入新增听写纪录的id号
	public static int insertDictationTime(DictationTime dt){
		DBConnect dbConnect = new DBConnect();
		String sql = "insert into dictation_time (courseClassId,content,time) values(?,?,?)";
		dbConnect.prepareStatement(sql);
		ResultSet rSet = null;
		int tid=0;
		try {
			setValue(dt, dbConnect);
			if(dbConnect.executeUpdate()){
				 rSet = dbConnect.getPreparedStatement().getGeneratedKeys();//返回插入数据后新增行的id
					if(rSet.next()){
						tid= rSet.getInt(1);
					}
			}
		} catch (Exception e) {
			// TODO: handle exception
		    e.printStackTrace();
		    System.out.println("insertDictaionTime ERROR");
		}finally{
			dbConnect.close();
		}
		return tid ;
	}
	
	/**
	 * 
	 * @param courseClassId
	 * @param stuyear
	 * @return
	 */
	public static int getCount(int courseClassId,int stuyear,String time1,String time2){
	    DBConnect dbConnect = new DBConnect();
	    String sTime = ParamStuyearControl.getStuyear(stuyear).getStartTime();
	    if(time1!=null&&!time1.equals("")){
	    	sTime = time1;
	    }
	    String eTime = ParamStuyearControl.getStuyear(stuyear).getEndTime();
	    if(time2!=null&&!time2.equals("")){
	    	eTime = time2;
	    }
	    int  count = 0;
	    String sql = "select count(id) from dictation_time where time between '"+sTime+"' and '"+eTime+"' and courseClassId = '"+courseClassId+"'";
	    dbConnect.prepareStatement(sql);
	    ResultSet rSet = null;
	    //System.out.println(sql);
	    try {
		rSet = dbConnect.executeQuery();
		if(rSet.next()){
		    count = rSet.getInt(1);
		}
	    } catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
		System.out.println("getCountByCourseIdAndStuyear ERROR");
	    }finally{
		dbConnect.close();
	    }
	    return count;
	}
	
	public static void setValue(DictationTime dt,DBConnect dbc){
		//调用此方法需注意字段顺序(与sql语句保持一致)
		int index=1;
		try{
		dbc.setInt(index++, dt.getCourseClassId());
		dbc.setString(index++,dt.getContent());
		dbc.setString(index++, dt.getTime());
		
	}catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
		System.out.println("setValue方法出错");
	}
	}
	
//	public static void main(String args[]){
//	    
//	    DictationTime dTime = new DictationTime();
//	    dTime.setContent("DDDD");
//	    dTime.setCourseClassId(2);
//	    dTime.setTime(DateTime.SimpleDate());
//	    System.out.println(insertDictationTime(dTime));
//	}

}
